<template>
  <div class="login-page">
    <a-row>
      <a-col :span="12" class="aside">
        <div class="aside-inner">
          <h2>这是我用过最好的建站工具</h2>
          <span class="text-white-70">王铁锤</span>
        </div>
      </a-col>
      <a-col :span="12" class="login-area">
        <a-form ref="formRef" layout="vertical" :model="form" :rules="rules">
          <h2>欢迎回来</h2>
          <p class="subTitle">使用手机和验证码登录</p>
          <a-form-item label="手机号码" name="cellphone">
            <a-input placeholder="请输入手机号" v-model:value="form.cellphone">
              <template v-slot:prefix
                ><UserOutlined style="color: rgba(0, 0, 0, 0.5)"></UserOutlined
              ></template>
            </a-input>
          </a-form-item>
          <a-form-item label="验证码" name="verifyCode">
            <a-input placeholder="请输入验证码" v-model:value="form.verifyCode">
              <template v-slot:prefix
                ><LockOutlined style="color: rgba(0, 0, 0, 0.5)"></LockOutlined
              ></template>
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" size="large" 
            @click="handleSubmit"
              :loading="isLoginLoading"
              >登录</a-button
            >
            <a-button size="large" style="margin-left: 20px"
            :disabled="codeButtonDisable" @click="getCode"
              >{{  counter===60?'获取验证码': `${counter}秒后重发` }}</a-button
            >
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import {
  Row as aRow,
  Col as aCol,
  Input as aInput,
  Button as aButton,
  Form as aForm,
  FormItem as aFormItem,
  Spin as aSpin,
  message,
} from "ant-design-vue";
import { LockOutlined, UserOutlined } from "@ant-design/icons-vue";
import { reactive, Ref, ref, watch,computed } from "vue";
import type { Rule, FormInstance} from "ant-design-vue/es/form";
import {useForm}  from "ant-design-vue/es/form";
import axios from "axios";
import { useStore } from "vuex";
import router from "@/routes";
import {GlobalDataProps} from "../store/index"

interface RuleFormInstance {
  validate: () => Promise<any>;
}
const store = useStore<GlobalDataProps>();
const isLoginLoading = computed(()=>{
  return store.getters.isOpLoading('login');
})

// 验证码过期时间
const counter =ref(60);
const formRef = ref() as Ref<RuleFormInstance>;
const form = reactive({
  cellphone: "",
  verifyCode: "",
});
const codeButtonDisable = computed(()=>{
  return !/^1[3-9]\d{9}$/.test(form.cellphone.trim()) || (counter.value<60)
})

const startCounter = ()=>{
  counter.value--
  const timer = setInterval(()=>{
    counter.value--
    if(counter.value === 0){
      counter.value = 60
      clearInterval(timer)
    }
  },1000);
}

const cellnumberValidor = (rule: Rule, value: string) => {
  return new Promise((resolve, reject) => {
    if (!value) {
      reject("手机号不能为空");
      return;
    }
    
    const passed = /^1[3-9]\d{9}$/.test(value.trim());
    setTimeout(() => {
      if (passed) {
        resolve("");
      } else {
        reject("手机号不正确");
      }
    }, 300);
  });
};
// 使用useForm 的hook时 才需要包装成reactive
const rules: Record<string, Rule[]> = reactive({
  cellphone: [
    { required: true, message: "手机号不能为空", trigger: "change" },
    // { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
    { asyncValidator: cellnumberValidor, trigger: "change" },
  ],
  verifyCode: [
    { required: true, message: "验证码不能为空", trigger: "change" },
    { pattern: /^[0-9]{4}$/, message: "验证码格式不正确", trigger: "change" },
  ],
});
const { validate, resetFields } = useForm(form, rules);
const handleSubmit = () => {
  // formRef.value.validate().then(() => {
  //   alert("passed");
  // });

  //使用hook 就不需要ref了
  console.log("开始验证表单");
  validate()
    .then(() => {
      // console.log("表单验证通过");
      // alert("passed");
      // resetFields();
      const payload = {
        phoneNumber: form.cellphone,
        veriCode: form.verifyCode
      }
      store.dispatch('loginAndFetch',{ data: payload}).then(()=>{
       message.success('登录成功',2);
       setTimeout(()=>{
        router.push('/');
       },2000)
      })
    })
    .catch(error => {
      console.error("表单验证失败:", error);
      message.error("表单验证失败，请检查输入");
    });
};

const getCode = ()=>{
  axios.post('/users/genVeriCode',{phoneNumber: form.cellphone})
  .then(()=>{
    message.success('验证码已发送，请注意查收',5)
    startCounter();
  })
}

</script>

<style scoped lang="less">
.aside-inner {
  height: 100vh;
  background: rgb(37, 36, 36);
  color: rgb(201, 200, 200);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .text-white-70 {
    color: rgb(167, 164, 164);
  }
}
.login-area {
  padding: 20vh 10vw;
  h2 {
    font-weight: 700;
  }
}
</style>
